package exp3;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.security.URIParameter;
import java.util.Optional;

@WebServlet(urlPatterns = {"/register_exp3"})
public class register_exp3 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String name = req.getParameter("name");
        String username=req.getParameter("user");
        String password = req.getParameter("password");
        String job=req.getParameter("job");
        String mail = req.getParameter("mail");
        File file = new File("informaion.txt");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (Exception e) {
                System.out.println("error to create");
                e.printStackTrace();
            }
        }
        else {
            String B,fault,fault2;
            System.out.println("文件已经存在");
            StringBuilder result = new StringBuilder();
            try {
                BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
                String s = null;
                while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                    result.append(s);
                    B=result.toString();
                    String BB[]=B.split(" ");
                    if(BB[0].equals(name))
                    {
                        resp.sendRedirect("http://localhost:8080/error_name.jsp");
                    }
                    result.delete(0,result.length());
                }
                br.close();
                FileWriter fileWritter = new FileWriter(file.getName(), true);
                fileWritter.write(name + " "+username+" "+ password + " " + mail+" "+job +"\n");
                fileWritter.close();
                System.out.println("write done");
                userdata user1;
                user1=new userdata(name,username,password,mail,job);
                HttpSession session;
                session=req.getSession();
                session.setAttribute("name",name);
                session.setAttribute("mail",mail);
                session.setAttribute("user",user1);
                resp.sendRedirect("http://localhost:8080/success.jsp");
            } catch (Exception e) {
                System.out.println("error to read");
            }
        }
    }
}